package com.lemon.kenhnhacvn;

import java.util.ArrayList;

import org.kobjects.base64.Base64;

import saucaca.CustomView.DrawerArrowDrawable;
import saucaca.Object.PlaylistObject;
import saucaca.Object.RingtoneObject;
import saucaca.Object.SongObject;
import saucaca.Service.MusicService;
import saucaca.Service.MusicService.MediaPlayerState;
import saucaca.Service.PlaylistManager;
import saucaca.Service.PlaylistManager.RepeatMode;
import saucaca.Service.Singleton;
import saucaca.Util.UtilMusic;
import saucaca.fragment.RingToneListSong;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.toolbox.ImageLoader;

@SuppressLint("NewApi")
public class MainActivity extends BaseActivity {
	String TAG = MainActivity.class.getSimpleName();
	private DrawerArrowDrawable drawerArrowDrawable;

	ImageView imgMenuNavigate;
	private TextView currentPlayingPosition1, txtSong, txtSinger;
	private TextView currentDuration1;
	private ImageView controlPlay, controlNext, controlPrev, imgMini_album;

	// private SeekBar songProgressBar;
	private SeekBar songProgressBar;
	private boolean songProgressBarIsBeingTouch;
	public PlaylistManager mPlaylistMgr;
	private MusicServiceStatusReceiver mStatusReceiver;
	private ProgressBar mPlaybackProgress;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		initView();
		final Resources resources = getResources();
		drawerArrowDrawable = new DrawerArrowDrawable(resources);
		drawerArrowDrawable.setStrokeColor(resources.getColor(R.color.white));

		myActionBar.setDrawerArrowDrawable(drawer, drawerArrowDrawable);
		myActionBar.setMenu(R.string.menu_home, true, true);
	}

	private void initView() {

		imgMini_album = (ImageView) findViewById(R.id.mini_picture_control);
		imgMenuNavigate = (ImageView) findViewById(R.id.menu_top_navigation_back);
		controlPlay = (ImageView) findViewById(R.id.btn_play);
		controlPrev = (ImageView) findViewById(R.id.btn_pre);
		controlNext = (ImageView) findViewById(R.id.btn_next);

		txtSong = (TextView) findViewById(R.id.txt_song);
		txtSinger = (TextView) findViewById(R.id.txt_singer);
		currentPlayingPosition1 = (TextView) findViewById(R.id.listening_control_textbufferStart1);
		currentDuration1 = (TextView) findViewById(R.id.listening_control_textbufferEnd1);
		mPlaybackProgress = (ProgressBar) findViewById(R.id.playback_seekbar2);
		songProgressBarIsBeingTouch = false;
		songProgressBar = (SeekBar) findViewById(R.id.listening_control_seekBars1);
		songProgressBar.setMax(100);
		songProgressBar.setOnSeekBarChangeListener(songProgressBar_changeListener);
		controlPrev.setOnClickListener(bt_Previous_click);
		controlPlay.setOnClickListener(bt_Play_click);
		controlNext.setOnClickListener(bt_Next_click);

		RelativeLayout relati = (RelativeLayout) findViewById(R.id.Bar_control_Layout);
		relati.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(getApplicationContext(), PlayActivity.class);
				startActivityForResult(intent, PLAY_RESULT);
			}
		});
	}

	int PLAY_RESULT = 1;

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == PLAY_RESULT) {
			if (resultCode == RESULT_OK) {
				try {
					SongObject object = (SongObject) data.getSerializableExtra("result");
					if (!BaseEngine.convertStringLongtoInteger(object.getISTONE()).equals("0")) {
						RingtoneObject ringtoneObject = new RingtoneObject();
						ringtoneObject.setSONG_ID(object.getSONG_ID());
						ringtoneObject.setTXNAME(object.getTXNAME());
						switchContent(RingToneListSong.class.getName(), ringtoneObject);
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			// if (resultCode == RESULT_CANCELED) {
			// //Write your code if there's no result
			// }
		}
		super.onActivityResult(requestCode, resultCode, data);
	}

	/**
	 * Restore preferences
	 */
	private void restorePreferences() {
		SharedPreferences sp = MainActivity.this.getSharedPreferences(MusicService.PREF_NAME, 0);

		// shuffle mode
		setShuffle(sp.getBoolean(MusicService.SETTING_SHUFFLE, false), false);

		// repeat mode
		String rp = sp.getString(MusicService.SETTING_REPEAT, RepeatMode.NoRepeat.toString());
		setRepeatMode(RepeatMode.valueOf(rp), true);
	}

	/**
	 * Save the preferences
	 */
	private void savePreferences() {
		// Save preference
		SharedPreferences sp = MainActivity.this.getSharedPreferences(MusicService.PREF_NAME, 0);
		SharedPreferences.Editor ed = sp.edit();
		if (mPlaylistMgr != null) {
			ed.putBoolean(MusicService.SETTING_SHUFFLE, mPlaylistMgr.isShuffle());
			ed.putString(MusicService.SETTING_REPEAT, mPlaylistMgr.getRepeatMode().toString());
			ed.commit();
		}
	}

	// Click listener của nút Next
	public OnClickListener bt_Next_click = new OnClickListener() {
		public void onClick(View v) {
			Intent i = new Intent(
			         new String(Base64.decode("Y29tLmFuZHJvaWQudmVuZGluZy5saWNlbnNpbmcuSUxpY2Vuc2luZ1NlcnZpY2U=")));
			i.setPackage("com.lemon.kenhnhacvn");
			i.setAction(MusicService.ACTION_NEXT);
			MainActivity.this.startService(i);
		}
	};

	// Click listener của nút play
	public OnClickListener bt_Play_click = new OnClickListener() {
		public void onClick(View v) {
			Intent i = new Intent(
			         new String(Base64.decode("Y29tLmFuZHJvaWQudmVuZGluZy5saWNlbnNpbmcuSUxpY2Vuc2luZ1NlcnZpY2U=")));
			i.setPackage("com.lemon.kenhnhacvn");
			if (MusicService.mState == MediaPlayerState.Playing) {
				i.setAction(MusicService.ACTION_PAUSE);
			} else {
				i.setAction(MusicService.ACTION_PLAY);
			}
			MainActivity.this.startService(i);
		}
	};

	// Click listener của nút previous
	public OnClickListener bt_Previous_click = new OnClickListener() {
		public void onClick(View v) {
			Intent i = new Intent(
			         new String(Base64.decode("Y29tLmFuZHJvaWQudmVuZGluZy5saWNlbnNpbmcuSUxpY2Vuc2luZ1NlcnZpY2U=")));
			i.setPackage("com.lemon.kenhnhacvn");
			i.setAction(MusicService.ACTION_PREVIOUS);
			MainActivity.this.startService(i);
		}
	};

	private void setRepeatMode(RepeatMode rp, boolean needtoast) {
		if (mPlaylistMgr == null) {
			return;
		}
		mPlaylistMgr.setRepeatMode(rp);
	}

	private void setShuffle(boolean s, boolean needtoast) {
		if (mPlaylistMgr == null)
			return;
		mPlaylistMgr.setShuffle(s);
	}

	// Seekbar change listener
	private OnSeekBarChangeListener songProgressBar_changeListener = new OnSeekBarChangeListener() {

		public void onStartTrackingTouch(SeekBar seekBar) {
			songProgressBarIsBeingTouch = true;
		}

		public void onStopTrackingTouch(SeekBar seekBar) {
			songProgressBarIsBeingTouch = false;

			Intent i = new Intent(
			         new String(Base64.decode("Y29tLmFuZHJvaWQudmVuZGluZy5saWNlbnNpbmcuSUxpY2Vuc2luZ1NlcnZpY2U=")));
			i.setPackage("com.lemon.kenhnhacvn");
			i.setAction(MusicService.ACTION_SEEK);

			Bundle b = new Bundle();
			b.putInt(MusicService.BKEY_PERCENTAGE, seekBar.getProgress());

			i.putExtras(b);
			MainActivity.this.startService(i);
		}

		public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {

		}
	};

//	@Override
//	public void onPause() {
//		MainActivity.this.unregisterReceiver(mStatusReceiver);
//		savePreferences();
//
//		if (MusicService.getState() != MediaPlayerState.Playing) {
//			Intent i = new Intent();
//			i.setClass(MainActivity.this, MusicService.class);
//			MainActivity.this.stopService(i);
//		}
//
//		super.onPause();
//	}

	@Override
	protected void onStart() {
		super.onStart();
		// register music service status reciever
		try {
			mStatusReceiver = new MusicServiceStatusReceiver();
			IntentFilter filter = new IntentFilter();
			filter.addAction(MusicService.STATUS_BC_NOW_PLAYING);
			filter.addAction(MusicService.STATUS_BC_PLAYTIME);
			filter.addAction(MusicService.STATUS_BC_ALL);
			filter.addAction(MusicService.STATUS_BC_PLAYMODE);
			filter.addAction(MusicService.STATUS_BC_NOWPLAYING_PLAYLIST);
			registerReceiver(mStatusReceiver, filter);
			// request status
//			Intent i = new Intent();
//			Intent i = new Intent(this, Class.forName(MainActivity.class.getName()));
			Intent i = new Intent(
			         new String(Base64.decode("Y29tLmFuZHJvaWQudmVuZGluZy5saWNlbnNpbmcuSUxpY2Vuc2luZ1NlcnZpY2U=")));
			i.setPackage("com.lemon.kenhnhacvn");
			i.setAction(saucaca.Service.MusicService.REQUEST_STATUS);
			MainActivity.this.startService(i);
		} catch (Exception e) {
			Log.e("", "onStart");
			e.printStackTrace();
		}
	}

	@Override
	protected void onStop() {
		super.onStop();
		savePreferences();
	}

	@Override
	protected void onResumeFragments() {
		mStatusReceiver = new MusicServiceStatusReceiver();
		IntentFilter filter = new IntentFilter();
		filter.addAction(MusicService.STATUS_BC_NOW_PLAYING);
		filter.addAction(MusicService.STATUS_BC_PLAYTIME);
		filter.addAction(MusicService.STATUS_BC_ALL);
		filter.addAction(MusicService.STATUS_BC_PLAYMODE);
		filter.addAction(MusicService.STATUS_BC_NOWPLAYING_PLAYLIST);
		MainActivity.this.registerReceiver(mStatusReceiver, filter);

		// request status
		try {
//			Intent i = new Intent();
			Intent i = new Intent(
			         new String(Base64.decode("Y29tLmFuZHJvaWQudmVuZGluZy5saWNlbnNpbmcuSUxpY2Vuc2luZ1NlcnZpY2U=")));
			i.setPackage("com.lemon.kenhnhacvn");
			i.setAction(saucaca.Service.MusicService.REQUEST_STATUS);
			MainActivity.this.startService(i);
			mPlaylistMgr = MusicService.getPlaylistManager();
			restorePreferences();
		} catch (Exception e) {
			Log.e("", "onResumeFragments");
			e.printStackTrace();
		}
		super.onResumeFragments();
	}

	private class MusicServiceStatusReceiver extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			Bundle b = intent.getExtras();
			Singleton singleton = Singleton.getInstance();
			if (mPlaylistMgr == null) {
				mPlaylistMgr = new PlaylistManager(singleton.getNowPlayingList());
				// restorePreferences();
			}
			if (action.equals(MusicService.STATUS_BC_ALL)) {
				// play-mode buttons
				if (mPlaylistMgr != null) {
					setShuffle(mPlaylistMgr.isShuffle(), false);
					setRepeatMode(mPlaylistMgr.getRepeatMode(), false);
				}
			}
			// Kiểm tra action để thể hiện tên bài hát
			if (action.equals(MusicService.STATUS_BC_NOW_PLAYING) || action.equals(MusicService.STATUS_BC_ALL)) {
				SongObject si = singleton.getCurrentSongObject();
				if (si != null) {
					if (singleton != null) {
						showPanelControl(true);
					}
					updateBarcontrol(si);
					songProgressBar.setEnabled(true);
				} else {
					MainActivity.this.showPanelControl(false);
//					if (mPlaylistMgr!=null && mPlaylistMgr.getCurrentSong()!=null) {
//						updateBarcontrol(mPlaylistMgr.getCurrentSong());
//					}
//					txtSong.setText("");
//					txtSinger.setText("");
//					currentPlayingPosition1.setText("");
//					currentDuration1.setText("");
//					songProgressBar.setEnabled(false);
				}
			}

			if (action.equals(MusicService.STATUS_BC_PLAYTIME) || action.equals(MusicService.STATUS_BC_ALL)) {
				// cap nhat seek bar
				int pos = b.getInt(MusicService.BKEY_CURSONG_POSITION);
				int len = b.getInt(MusicService.BKEY_CURSONG_DURATION);
				currentPlayingPosition1.setText(UtilMusic.milliSecondsToTimer(pos));
				currentDuration1.setText(UtilMusic.milliSecondsToTimer(len));
				if (!songProgressBarIsBeingTouch) {
					songProgressBar.setProgress(UtilMusic.getProgressPercentage(pos, len));
					mPlaybackProgress.setProgress(UtilMusic.getProgressPercentage(pos, len));
					Drawable ii = getResources().getDrawable(R.drawable.ctbh_icon_timeline);
					songProgressBar.setThumb(ii);
				}
			}

			// Update state of play/pause button
			MediaPlayerState mState = (MediaPlayerState) b.getSerializable(MusicService.BKEY_STATE);
			if (mState == MediaPlayerState.Paused || mState == MediaPlayerState.Stopped) {
				controlPlay.setImageResource(R.drawable.playbar_button_play);
			} else if (mState == MediaPlayerState.Playing) {
				controlPlay.setImageResource(R.drawable.playbar_button_pause);
			}
		}
	}

	public void SendPlaylistAndplay(ArrayList<SongObject> listSongs, int index) {
		if (mPlaylistMgr != null) {
			if (!BaseEngine.compareList(mPlaylistMgr.getArrayList(), listSongs)) {
				mPlaylistMgr.setArrayList(listSongs);
				send();
				play(listSongs, index);
			} else {
				play(listSongs, index);
			}
		} else {
			mPlaylistMgr = new PlaylistManager(listSongs);
			send();
			play(listSongs, index);
		}
	}

	private void send() {
		Singleton s = Singleton.getInstance();
		s.setPlaylistManager(mPlaylistMgr);
		s.setNowPlayingList(mPlaylistMgr.getArrayList());
		try {
//			Intent i = new Intent();
			Intent i = new Intent(
			         new String(Base64.decode("Y29tLmFuZHJvaWQudmVuZGluZy5saWNlbnNpbmcuSUxpY2Vuc2luZ1NlcnZpY2U=")));
			i.setPackage("com.lemon.kenhnhacvn");
			i.setAction(MusicService.SUPPLY_PLAYLIST);
			MainActivity.this.startService(i);
		} catch (Exception e) {
		}
	}

	public void play(ArrayList<SongObject> listSongs, int index) {
		SongObject si = (SongObject) listSongs.get(index);
		Singleton singleton = Singleton.getInstance();
		singleton.setCurrentSongObject(si);
		singleton.setCurrentIndex(index);
		updateBarcontrol(si);
		try {
//			Intent i1 = new Intent();
			Intent i1 = new Intent(
			         new String(Base64.decode("Y29tLmFuZHJvaWQudmVuZGluZy5saWNlbnNpbmcuSUxpY2Vuc2luZ1NlcnZpY2U=")));
			i1.setPackage("com.lemon.kenhnhacvn");
			i1.setAction(MusicService.ACTION_PLAY_SPECIFIC_SONG);
			MainActivity.this.startService(i1);
		} catch (Exception e) {
		}
	}

	public void play(int index) {
		SongObject si = (SongObject) mPlaylistMgr.getArrayList().get(index);
		Singleton singleton = Singleton.getInstance();
		singleton.setCurrentSongObject(si);
		singleton.setCurrentIndex(index);
		updateBarcontrol(si);
//		Intent i1 = new Intent();
		Intent i1 = new Intent(
		         new String(Base64.decode("Y29tLmFuZHJvaWQudmVuZGluZy5saWNlbnNpbmcuSUxpY2Vuc2luZ1NlcnZpY2U=")));
		i1.setPackage("com.lemon.kenhnhacvn");
		i1.setAction(MusicService.ACTION_PLAY_SPECIFIC_SONG);
		MainActivity.this.startService(i1);
	}

	public void updateBarcontrol(SongObject si) {
		imgMini_album.setImageResource(R.drawable.cd_default);
		txtSong.setText(si.getTXNAME());
		txtSinger.setText(si.getNAME_SINGERS());
		if (!si.getFormNet()) {
			Bitmap bm = BitmapFactory.decodeFile(si.getAVATAR());
			if (bm != null) {
				@SuppressWarnings("deprecation")
				BitmapDrawable bmpDraw = new BitmapDrawable(bm);
				imgMini_album.setImageDrawable(bmpDraw);
			}
		} else {
			imageLoader.get(si.getAVATAR_SINGER(), ImageLoader.getImageListener(imgMini_album,
			         R.drawable.ic_default, R.drawable.ic_default));
		}
	}

	public void onPlayListClick(View v) {
		if (mPlaylistMgr != null)
			ShowPlayListSongQueue(MainActivity.this, mPlaylistMgr.getArrayList());
	}

	public void ShowPlayListSongQueue(final Activity a, final ArrayList<SongObject> playlist) {
		AlertDialog.Builder builder = new AlertDialog.Builder(a);
		builder.setTitle("Danh sách phát");

		if (playlist == null || playlist.size() == 0) {
			Toast.makeText(a, "Trống!", Toast.LENGTH_SHORT).show();
			return;
		}
		String[] array = new String[playlist.size()];
		for (int i = 0; i < playlist.size(); i++) {
			array[i] = playlist.get(i).getTXNAME();
		}

		builder.setItems(array, new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int position) {
				play(playlist, position);
			}
		});
		builder.create().show();
	}

	public void ShowPlayList(final Activity a, final ArrayList<PlaylistObject> playlist) {
		AlertDialog.Builder builder = new AlertDialog.Builder(a);
		builder.setTitle("Danh sách phát");

		if (playlist == null || playlist.size() == 0) {
			Toast.makeText(a, "Trống!", Toast.LENGTH_SHORT).show();
			return;
		}
		String[] array = new String[playlist.size()];
		for (int i = 0; i < playlist.size(); i++) {
			array[i] = playlist.get(i).getTXNAME();
		}

		builder.setItems(array, new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int position) {
				Toast.makeText(a, "Trống!", Toast.LENGTH_SHORT).show();
			}
		});
		builder.create().show();
	}

	private static long back_pressed;

	@Override
	public void onBackPressed() {
		if (mCurrentFragment != null) {
			if (mCurrentFragment.getClass().getName() == mFragmentList.get(0).getClass().getName()) {
				if (back_pressed + 2000 > System.currentTimeMillis()) {
					finish();
				} else
					Toast.makeText(getBaseContext(), "Press back again to exit!", Toast.LENGTH_SHORT).show();
				back_pressed = System.currentTimeMillis();
			} else if (mFragmentList.size() > 1) {
				showprevousFragment();
			} else {
				if (back_pressed + 2000 > System.currentTimeMillis()) {
					finish();
				} else
					Toast.makeText(getBaseContext(), "Press back again to exit!", Toast.LENGTH_SHORT).show();
				back_pressed = System.currentTimeMillis();
			}
		} else
			finish();
	}
}
